package com.salon.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.salon.modules.sys.entity.SysRoleMenuEntity;
import com.salon.modules.sys.mapper.SysRoleMenuMapper;
import com.salon.modules.sys.service.ISysRoleMenuService;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 角色与菜单对应关系
 */
@Service("sysRoleMenuService")
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenuEntity>
        implements ISysRoleMenuService {

    @Override
    public List<Long> listMenuIdsByRoleId(Long roleId) {
        return baseMapper.listMenuIdsByRoleId(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(Long roleId, List<Long> menuIdList) {
        //先删除角色与菜单关系
        this.deleteBatch(new Long[]{roleId});
        if (CollectionUtils.isEmpty(menuIdList)) {
            return;
        }
        //保存角色与菜单关系
        for (Long menuId : menuIdList) {
            SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
            sysRoleMenuEntity.setMenuId(menuId);
            sysRoleMenuEntity.setRoleId(roleId);
            this.save(sysRoleMenuEntity);
        }
    }

    @Override
    public int deleteBatch(Long[] roleIds) {
        LambdaQueryWrapper<SysRoleMenuEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysRoleMenuEntity::getRoleId, CollectionUtils.arrayToList(roleIds));
        return baseMapper.delete(queryWrapper);
    }

}
